<template>
  <div class="table-wrapper">
    <div class="table-title">{{ tableParams.tableTitle }}</div>
    <div class="table-container">
      <table class="data-table">
        <thead :style="{ height: tableParams.headerHeight + 'px' }">
          <tr>
            <th
              v-for="column in columns"
              :key="column.prop"
              :style="{ height: tableParams.headerHeight, backgroundColor: headerBgColor, color: '#fff', width: column.widthPercent + '%', fontSize: column.headerFontSize + 'px' }"
            >
              {{ column.label }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in tableData" :key="index">
            <td v-for="column in columns" :key="column.prop">
              <span
                :style="{
                  color: column.colorShow || row[column.prop + '是否标红'] ? column.colorShow || '#ee6666' : '#000',
                  fontSize: column.contentFontSize + 'px',
                  fontWeight: '600',
                }"
              >
                {{ truncateToTwoDecimals(row[column.prop]) }}
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DataTable',
  props: {
    tableParams: {
      type: Object,
      default: () => ({
        // 表头高度
        headerHeight: 30,
        // 表格标题
        tableTitle: '',
      }),
    },
    // 表格数据
    tableData: {
      type: Array,
      required: true,
      default: () => [
        {
          category: '1',
          primary: '1',
          secondary: '1',
          ratio: '1',
        },
        {
          category: '2',
          primary: '2',
          secondary: '2',
          ratio: '2',
        },
        {
          category: '3',
          primary: '3',
          secondary: '3',
          ratio: '3',
        },
        {
          category: '4',
          primary: '4',
          secondary: '4',
          ratio: '4',
        },
        {
          category: '5',
          primary: '5',
          secondary: '5',
          ratio: '5',
        },
        {
          category: '6',
          primary: '6',
          secondary: '6',
          ratio: '6',
        },
        {
          category: '7',
          primary: '7',
          secondary: '7',
          ratio: '7',
        },
        {
          category: '8',
          primary: '8',
          secondary: '8',
          ratio: '8',
        },
      ],
    },
    // 表格列配置
    columns: {
      type: Array,
      required: true,
      default: () => [
        { prop: 'category', label: '月份', width: '180' },
        { prop: 'primary', label: '销售额', width: '180' },
        { prop: 'secondary', label: '趋势值', width: '180' },
        { prop: 'ratio', label: '同比增长', width: '180' },
      ],
    },
    // 表头背景色
    headerBgColor: {
      type: String,
      default: '#4874cb',
    },
    // PPT导出配置
    pptOptions: {
      type: Object,
      default: () => ({
        x: 0.5, // X轴位置
        y: 1.2, // Y轴位置
        w: 9, // 宽度
        h: 6, // 高度
        title: {
          // 标题配置
          x: 0.5,
          y: 0.5,
          fontSize: 24,
          color: '363636',
          bold: true,
        },
        table: {
          // 表格配置
          colW: [2.25, 2.25, 2.25, 2.25],
          rowH: 0.1,
          // 表格内容配置
          content: {
            fontSize: 14,
            color: '000000',
            bold: true,
          },
          // 表格标题配置
          title: {
            fontSize: 14,
            color: 'ffffff',
          },
          // 表格边框样式
          borderStyle: {
            color: '000000',
          },
          // 表格垂直对齐方式(middle, top, bottom)
          valign: 'middle',
          // 表格水平对齐方式(left, center, right)
          align: 'center',
          // 自动分页
          autoPage: true,
          // 自动分页标题是否显示
          autoPageRepeatHeader: true,
          // 自动分页标题行数
          autoPageHeaderRows: 1,
        },
      }),
    },
  },
  methods: {
    /**
     * 保留2位小数
     * @param {string} input 输入值
     * @returns {string} 保留2位小数的值
     */
    truncateToTwoDecimals(input) {
      // 1. 检查是否是字符串，并且包含小数点（如 "2.5666"）
      if ((typeof input === 'string' || typeof input === 'number') && input.toString().includes('.')) {
        // 尝试转换为数字
        const num = parseFloat(input);
        // 如果是合法数字，截断小数部分
        if (!isNaN(num) && isFinite(num)) {
          return Math.floor(num * 100) / 100;
        }
      }
      // 2. 其他情况（整数、非数字、中文、符号等）直接返回
      return input;
    },
    /**
     * 导出为PPT
     * @param {Object} pptx pptxgen实例
     * @param {Object} slide 当前幻灯片实例
     * @description 将表格导出为PPT
     */
    exportToPPT(pptx, slide) {
      let arrRowsHead = [];
      // 构建表头行
      let columnsList = [];
      this.columns.forEach(column => {
        //标题
        columnsList.push({
          text: column.label,
          options: {
            fill: this.headerBgColor.replace('#', ''),
            color: this.pptOptions.table.title.color,
            valign: this.pptOptions.table.valign,
            align: this.pptOptions.table.align,
            fontSize: this.pptOptions.table.title.fontSize,
          },
        });
      });
      arrRowsHead.push(columnsList);
      // 添加数据行
      this.tableData.forEach((row, idx) => {
        const rowData = [];
        this.columns.forEach(column => {
          //数据(保留2位小数)
          rowData.push({
            text: this.truncateToTwoDecimals(row[column.prop]) != 0 ? this.truncateToTwoDecimals(row[column.prop]) : '0',
            options: {
              fill: idx % 2 === 0 ? 'f5f5f5' : 'ffffff',
              color: row[column.prop + '是否标红'] ? 'ee6666' : this.pptOptions.table.content.color,
              valign: this.pptOptions.table.valign,
              align: this.pptOptions.table.align,
              fontSize: column.pptContentFontSize || this.pptOptions.table.content.fontSize,
              bold: this.pptOptions.table.content.bold,
            },
          });
        });
        arrRowsHead.push(rowData);
      });
      // 使用配置添加表格到PPT
      slide.addTable(arrRowsHead, {
        x: this.pptOptions.x,
        y: this.pptOptions.y,
        w: this.pptOptions.w,
        h: this.pptOptions.h,
        colW: this.pptOptions.table.colW,
        rowH: this.pptOptions.table.rowH,
        // 表格边框颜色
        border: { color: this.pptOptions.table.borderStyle.color },
        // 自动分页是否开启
        autoPage: this.pptOptions.table.autoPage,
        // 表格边距
        margin: [0, 0, 0, 0],
        // 自动分页标题是否显示
        autoPageRepeatHeader: this.pptOptions.table.autoPageRepeatHeader,
        // 自动分页标题行数
        autoPageHeaderRows: this.pptOptions.table.autoPageHeaderRows,
      });
    },
  },
};
</script>

<style lang="less" scoped>
.table-wrapper {
  height: 100%;
  .table-title {
    height: 40px;
    line-height: 40px;
    font-size: 18px;
    color: #363636;
    font-weight: bold;
    text-align: center;
  }
  .table-container {
    width: 100%;
    height: calc(100% - 40px);
  }

  .data-table {
    width: 100%;
    height: 100%;
    border-collapse: collapse;

    th,
    td {
      border: 1px solid #000;
      padding: 0 8px;
      text-align: center;
    }

    th {
      text-align: center;
    }

    tbody tr:nth-child(even) {
      background-color: #f5f5f5;
    }

    tbody tr:nth-child(odd) {
      background-color: #ffffff;
    }
  }
}
</style>
